package com.fy.shardingsphere.service;

import com.fy.shardingsphere.entity.Order;
import com.fy.shardingsphere.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    private static final int MAX_RETRY_TIMES = 3;
    private static final long RETRY_DELAY = 1000L; // 1秒

    @Transactional
    public void createOrder(Order order) {
        int retryCount = 0;
        while (retryCount < MAX_RETRY_TIMES) {
            try {
                orderMapper.insert(order);
                return;
            } catch (Exception e) {
                retryCount++;
                log.warn("创建订单失败，正在进行第{}次重试，region={}", retryCount, order.getRegion());
                if (retryCount >= MAX_RETRY_TIMES) {
                    throw new RuntimeException("创建订单失败，超过最大重试次数", e);
                }
                try {
                    Thread.sleep(RETRY_DELAY);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("重试被中断", ie);
                }
            }
        }
    }
} 